package com.yunhe.inspect.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunhe.common.model.mybatis.PageResult;
import com.yunhe.inspect.domain.DataInspectOrder;
import com.yunhe.inspect.domain.InspectProcess;
import com.yunhe.inspect.domain.RectificationSheet;
import com.yunhe.inspect.model.ExportHistoryRectificationSheetVO;
import com.yunhe.inspect.model.ExportHistoryVO;
import com.yunhe.inspect.model.HistoryQueryCondition;
import com.yunhe.inspect.model.HistoryResponseVO;
import com.yunhe.inspect.model.InspectOrderItem;
import com.yunhe.inspect.repository.DataInspectOrderItemRepository;
import com.yunhe.inspect.repository.DataInspectOrderRepository;
import com.yunhe.inspect.repository.RectificationSheetRepository;
import com.yunhe.inspect.service.HistoryService;
import com.yunhe.inspect.service.InspectProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class HistoryServiceImpl implements HistoryService {
    @Autowired
    private DataInspectOrderRepository dataInspectOrderRepository;
    @Autowired
    private DataInspectOrderItemRepository dataInspectOrderItemRepository;
    @Autowired
    private InspectProcessService inspectProcessService;
    @Autowired
    private RectificationSheetRepository rectificationSheetRepository;

    @Override
    public PageResult getListPage(HistoryQueryCondition queryVO) {
        PageHelper.startPage(queryVO.getPage(), queryVO.getSize());
        queryVO.setExpirationTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
        List<HistoryResponseVO> voList = dataInspectOrderRepository.getHistoryList(queryVO);
        PageInfo<HistoryResponseVO> pageInfo = new PageInfo<>(voList);
        return new PageResult(queryVO.getPage(), queryVO.getSize(), (int)pageInfo.getTotal(), voList);
    }

    @Transactional
    @Override
    public void delete(String ids, Long userId) {
        if(StrUtil.isBlank(ids)){
            return;
        }
        String[] idArr = ids.split(",");
        List<Integer> idList = new ArrayList<>();
        Arrays.stream(idArr).forEach(e->idList.add(Integer.valueOf(e)));
        dataInspectOrderRepository.deleteDataInspectOrderByIds(idList, userId);
    }

    @Override
    public ExportHistoryVO detail(Long id) {
        ExportHistoryVO vo = new ExportHistoryVO();
        handleDataInspectOrder(vo, id); //主表信息
        handleCheckItems(vo, id); //检查项目列表与检查结果列表
        handleCheckResultSheet(vo, id); //整改单情况
        return vo;
    }
    //整改单情况
    private void handleCheckResultSheet(ExportHistoryVO vo, Long id) {
        List<RectificationSheet> rectificationSheetList =  rectificationSheetRepository.getRectificationHistoryByInspectOrderId(id.intValue());
        if(Objects.isNull(rectificationSheetList) || rectificationSheetList.isEmpty() ){ //无整改单 return
            return;
        }

        //处理整改单列表
        List<ExportHistoryRectificationSheetVO> itemList = new ArrayList<>();
        rectificationSheetList.forEach(e->{
            ExportHistoryRectificationSheetVO item = new ExportHistoryRectificationSheetVO();
            item.setLimitTime(handleTimeFmt(new SimpleDateFormat("yyyy-MM-dd").format(e.getRectificationDeadline())));//整改时间
            if(StrUtil.isNotBlank(e.getImages())){
                item.setImgUrlList(Arrays.asList(e.getImages().split(","))); //图片
            }
            item.setCheckResult(e.getHiddenDanger()); //整改的问题
            item.setRectificationContent(e.getRectificationContent()); //整改内容

            //复审情况
            InspectProcess inspectProcess = inspectProcessService.getListByRectificationId(e.getId());
            if(Objects.nonNull(inspectProcess)){
                item.setReviewResult(inspectProcess.getReviewSuggestion()); //复审结果
                item.setReviewTime(handleTimeFmt(new SimpleDateFormat("yyyy-MM-dd").format(inspectProcess.getCreateTime()))); //复审时间
            } else {
                item.setReviewResult("/"); //复审结果
                item.setReviewTime("/"); //复审时间
            }

            itemList.add(item);
        });

        vo.setRectificationSheetList(itemList);
    }

    //检查项目列表与检查结果列表
    private void handleCheckItems(ExportHistoryVO vo, Long orderId) {
        //查询工单对应的项目集合
        List<InspectOrderItem> list = dataInspectOrderItemRepository.searchDataInspectOrderItemByOrderId(orderId.intValue());
        vo.setInspectOrderItems(Optional.ofNullable(list).orElse(new ArrayList<>(0)));
        /*if(Objects.isNull(list)){
            vo.setInspectOrderItems(new ArrayList<>(0));
            return;
        }*/

        /*List<String> itemList = new ArrayList<>(); //检查的项目集合
        List<String> resultList = new ArrayList<>(); //检查的结果集合
        list.forEach(e->{
            itemList.add(e.getItemContent());
            resultList.add(e.getItemValue());
        });
        vo.setItemList(itemList);
        vo.setResultList(resultList);*/
    }
    //HistoryResponseVO 处理主表信息
    private DataInspectOrder handleDataInspectOrder(ExportHistoryVO vo, Long id) {
        DataInspectOrder d = dataInspectOrderRepository.searchDataInspectOrderByPrimaryKey(id.intValue());
        Assert.isTrue(Objects.nonNull(d), "未查到工单信息："+id);
        vo.setTitle(d.getInspectOrderTitle());
        vo.setNumber(d.getInspectOrderNo());
        vo.setCompanyName(d.getCompanyName());
        vo.setOfficeName(d.getOfficeName());
        vo.setCreateTime(handleTimeFmt(d.getInspectOrderGenerationTime()));
        if(Objects.nonNull(d.getInspectOrderInspector())){ //检查人
            vo.setCheckPerson(String.valueOf(d.getInspectOrderInspector()));
        }
        if(Objects.nonNull(d.getInspectOrderSubject())){ //受检人
            vo.setTestedPerson(String.valueOf(d.getInspectOrderSubject()));
        }
        if(Objects.nonNull(d.getInspectedPersonSignature())){ //受检人签名图片
            vo.setInspectedPersonSignature(d.getInspectedPersonSignature());
        }
        return d;
    }

    //可能获取到的时间格式不一致 统一转换成yyyy/MM/dd
    private String handleTimeFmt(String time){
        String fmtTime = "";
        for(int i=0; i<time.length(); i++){
            if(Character.isSpaceChar(time.charAt(i))) {
                break;
            }
            if(Character.isDigit(time.charAt(i))){ //是否为数字
                fmtTime += time.charAt(i);
            } else {
                fmtTime += "/";
            }
        }
        return fmtTime;
    }
}
